package org.ydsw.data.manage.schedule;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.ydsw.data.manage.config.ThreadPoolConfig;
import org.ydsw.data.manage.entity.ScheduleJobEntity;
import org.ydsw.data.manage.entity.ScheduleJobLogEntity;
import org.ydsw.data.manage.service.ScheduleJobLogService;
import org.ydsw.data.manage.utils.DateUtil;


import java.util.HashMap;
import java.util.Map;

/**
 * 执行具体的定时任务
 * 本方法类写具体的执行逻辑
 * @author admin
 * @date 2021年01月05日
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

    @Autowired
    private ScheduleJobLogService scheduleJobLogService;

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
                .get(ScheduleJobEntity.JOB_PARAM_KEY);
        //数据库保存执行记录
        ScheduleJobLogEntity logEntity = new ScheduleJobLogEntity();
        logEntity.setJobId(scheduleJob.getJobId());
        logEntity.setBeanName(scheduleJob.getBeanName());
        logEntity.setMethodName(scheduleJob.getMethodName());
        logEntity.setParams(scheduleJob.getParams());
        logEntity.setCreateTime(DateUtil.getCurrentTime());
        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams());
            ThreadPoolConfig.schedulerThreadPool().execute(task);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            logEntity.setTimes((int) times);
            //任务状态: 0：成功 1：失败
            logEntity.setStatus(0);
        } catch (Exception e) {
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            logEntity.setTimes((int) times);
            //任务状态 :0：成功  1：失败
            logEntity.setStatus(1);
            logEntity.setError(e.getMessage());
            Map<String,Object> params = new HashMap();
            params.put("beanName",logEntity.getBeanName());
            params.put("methodName",logEntity.getMethodName());
            params.put("message",e.getMessage());
            params.put("time", DateUtil.getStrByDate(logEntity.getCreateTime()));

        } finally {
            scheduleJobLogService.save(logEntity);
            log.info("ScheduleJob执行完毕，job id: {}, 等待调度中....", scheduleJob.getJobId());
        }
    }
}
